package com.eco.fanliapp.admin.controller.web;

import com.eco.fanliapp.admin.annotation.SysLogAnnotation;
import com.eco.fanliapp.admin.common.BaseController;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.SyAdminLoginIpMapper;
import com.eco.fanliapp.entity.Administrator;
import com.eco.fanliapp.entity.AppUser;
import com.eco.fanliapp.entity.SysLog;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.ComputeUtil;
import com.eco.fanliapp.utils.MapValueHelper;
import com.eco.fanliapp.vo.UserVO;
import com.eco.fanliapp.vo.WithdrawalInfo;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/web/user")
public class UserController extends BaseController {

    @Autowired
    private IAppUserService userService ;
    @Autowired
    private IAppWithdrawalService withdrawalService;
    @Autowired
    private SysLogCommon sysLogCommon;
    @Autowired
    private IAdministratorService administratorService;
    @Autowired
    private IAppOrderDetailService orderDetailService ;
    @Autowired
    private ISyUserMoneyLogService syUserMoneyLogService ;
    @Autowired
    private SyAdminLoginIpMapper syAdminLoginIpMapper;


    /**
     * 查询用户列表
     * @return
     */
    @GetMapping("/findUserList")
    public ServerResponse<PageInfo> findUserList(String userName,@RequestParam(defaultValue = "1") Integer currentPage , @RequestParam(defaultValue = "5") Integer pageSize){
        Integer companyId =  getAuthentication().getCompanyId();
        if(companyId == 1){
            companyId = null;
        }
        return userService.selectAppUserListByPaging(currentPage, pageSize,companyId,userName);

    }

    /**
     * 禁用  用户
     */
    @SysLogAnnotation(value = "禁用用户",userType = 2)
    @RequestMapping(method = RequestMethod.POST,value = "/forbid")
    public ServerResponse asda(@RequestBody AppUser appUser){
        UserVO authentication = getAuthentication();
        AppUser appUser1 = userService.getById(appUser.getTableId());
        Administrator administrator = administratorService.getById(authentication.getUserId());
        SysLog sysLog = new SysLog();
        sysLog.setUserId(authentication.getUserId());
        if(appUser.getEnable()==0)
            sysLog.setMethodExplain(administrator.getAdminitratorName()+"禁用了"+appUser1.getUserName());
        if(appUser.getEnable()==1)
            sysLog.setMethodExplain(administrator.getAdminitratorName()+"启用了"+appUser1.getUserName());
        int i = userService.updateAppUser(appUser);
        if (i >0) {
            sysLog.setResponseParams("成功");
            sysLogCommon.save(sysLog);
            return ServerResponse.createBySuccess();
        }
        sysLog.setResponseParams("失败");
        sysLogCommon.save(sysLog);
        return ServerResponse.createByError();

    }

    /**
     * 查询用户详情
     * @return
     */
    @GetMapping("/findUserDetails")
    public ServerResponse<WithdrawalInfo> findUserDetails(Long userId, @RequestParam(defaultValue = "1") int currentPage, @RequestParam(defaultValue = "5") int pageSize){


        WithdrawalInfo withdrawalInfo = userService.selectAppUserByTaoBaoUserId(userId,currentPage,pageSize);

        return ServerResponse.createBySuccess("查询用户详情",withdrawalInfo);
    }


    @GetMapping("/findUserOnesFen")
    public ServerResponse<PageInfo> findUserOnesFen(Long userId, @RequestParam(defaultValue = "1") int currentPage, @RequestParam(defaultValue = "5") int pageSize){

        return userService.findUserOnesFen(userId,currentPage,pageSize);
    }
    /**
     * 查询用户订单详情
     * @return
     */
    @GetMapping("/findUserOrderDetails")
    public ServerResponse<PageInfo> findUserOrderDetails(Long userId, @RequestParam(defaultValue = "1") int currentPage, @RequestParam(defaultValue = "5") int pageSize){

        return orderDetailService.selectAppOrderDetailListNew(currentPage,pageSize,userId);
    }

    /**
     * 查询用户提现详情
     * @return
     */
    @GetMapping("/findUserGetMoneyDetails")
    public ServerResponse<PageInfo> findUserGetMoneyDetails(Long userId, @RequestParam(defaultValue = "1") int currentPage, @RequestParam(defaultValue = "5") int pageSize){

        return withdrawalService.findUserGetMoneyDetails(currentPage,pageSize,userId);
    }

    public String getLocalIp(HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        String forwarded = request.getHeader("X-Forwarded-For");
        String realIp = request.getHeader("X-Real-IP");

        String ip = null;
        if (realIp == null) {
            if (forwarded == null) {
                ip = remoteAddr;
            } else {
                ip = remoteAddr + "/" + forwarded.split(",")[0];
            }
        } else {
            if (realIp.equals(forwarded)) {
                ip = realIp;
            } else {
                if(forwarded != null){
                    forwarded = forwarded.split(",")[0];
                }
                ip = realIp + "/" + forwarded;
            }
        }
        System.out.println("ip为+++++++++++++++++{+"+ip+"+}+++++++++");
        return ip;
    }

    /**
     * 修改用户的可提金额
     * @return
     */
    @SysLogAnnotation(value = "修改用户的可提金额",userType = 2)
    @PostMapping("/updateBalance")
    public ServerResponse<AppUser> updateUserBalance(HttpServletRequest request,@RequestBody  HashMap<String,Object> params){
        //校验ip是否合法
        String syAdminLoginIp = syAdminLoginIpMapper.selectAdminIp();
        if (!getLocalIp(request).equals(syAdminLoginIp)) {
            return ServerResponse.createByErrorCodeMessage(400, "此IP限制登录,请联系开发人员");
        }

        MapValueHelper mapValueHelper = new MapValueHelper(params);
        AppUser tableIdUser = userService.selectAppUserById(mapValueHelper.getLong("tableId"));
        //获取改前余额
        BigDecimal balanceBefore = tableIdUser.getBalance();
        //修改后余额
		BigDecimal balance = mapValueHelper.getBigDecimal("balance");
        //计算变化的金额
        double sub = ComputeUtil.sub(balance.doubleValue(), balanceBefore.doubleValue());
        double abs = Math.abs(sub);
        //校验修改的金额是否合理
        if(abs == 0){
            return  ServerResponse.createByErrorMessage("修改前后金额一致，不允许修改");
        }
		AppUser appUser =  new AppUser();
        appUser.setTableId(mapValueHelper.getLong("tableId"));
        appUser.setBalance(balance);
        appUser.setPhoneNumber(mapValueHelper.getString("phoneNumber"));
        int updateNum = userService.updateAppUser(appUser);
        if (updateNum > 0){
            //判断该次操作是加还是减
            Integer logStatus = 1;//默认减
            if(ComputeUtil.compare(balance.doubleValue(),balanceBefore.doubleValue())>0){
                logStatus = 0;
            }
            //插入余额日志
            syUserMoneyLogService.addSyUserMoneyLogNew(tableIdUser.getUserId(),balanceBefore,new BigDecimal(abs),
                    mapValueHelper.getString("remark"),3,logStatus,balance);
            return ServerResponse.createBySuccessMessage("修改成功");
        }
        return  ServerResponse.createBySuccessMessage("修改失败");
    }



    /**
     * 根据用户名称的关键字模糊查询用户列表
     * @param  userName
     * @return
     */
    @RequestMapping(value = "/findUserListByUserName",method = RequestMethod.GET)
    public ServerResponse<PageInfo> findUserListByUserName(String userName, @RequestParam(defaultValue = "1") Integer currentPage , @RequestParam(defaultValue = "5") Integer pageSize){
        int companyId = getAuthentication().getCompanyId();
        return userService.selectAppUserListByUserName(userName, currentPage, pageSize,companyId);


    }

    /**
     * 根据上级微信id查询一级粉丝详情
     * @return
     */
    @GetMapping("/findPrimaryFansDetails")
    public ServerResponse<List> findPrimaryFansDetails(String superInviteCode){

        List<AppUser> appUsers = userService.selectFansBySuperInviteCode(superInviteCode);

        return ServerResponse.createBySuccess("查询用户详情",appUsers);
    }

    /**
     * 根据上级微信id查询二级粉丝详情
     * @param superInviteCode
     * @return
     */
    @GetMapping("/findSecondaryFansDetails")
    public ServerResponse<Map> findSecondaryFansDetails(String superInviteCode){

        // 查询一级粉丝列表
        List<AppUser> primaryAppUsers = userService.selectFansBySuperInviteCode(superInviteCode);
        HashMap<String, List> secondaryFansMap = new HashMap<>();
        for (AppUser appUser : primaryAppUsers) {
            // 查询二级粉丝列表
            String secondarySuperInviteCode = appUser.getMeInviteCode();
            List<AppUser> secondaryAppUsers =  userService.selectFansBySuperInviteCode(secondarySuperInviteCode);
            secondaryFansMap.put("secondaryFansMap",secondaryAppUsers);
        }
        return ServerResponse.createBySuccess("查询用户详情",secondaryFansMap);
    }

    /**
     * 根据微信ID下载用户
     * @param wechatUnionid
     * @return
     */
    @SysLogAnnotation(value = "根据微信ID下载用户",userType = 2)
    @GetMapping("/downloadAppUserByWechatUnionid")
    public ServerResponse downloadAppUserByWechatUnionid(String wechatUnionid){

        boolean flag = userService.downloadUserInformationByWechatUnionid(wechatUnionid);
        if (flag){
            return  ServerResponse.createBySuccessMessage("下载用户信息成功！");
        }
        return  ServerResponse.createByErrorMessage("用户不存在！");
    }

    /**
     * 下载用户信息
     * @return
     */
    @SysLogAnnotation(value = "下载用户信息",userType = 2)
    @GetMapping("/downloadAppUser")
    public void downloadAppUser(HttpServletResponse response,String username){

        userService.downloadUserInformation(response,username);
    }

    @SysLogAnnotation(value = "upWxNicke",userType = 2)
    @RequestMapping(method = RequestMethod.POST, value = "/upWxNicke")
    public ServerResponse upWechatNickname(@RequestBody AppUser appUser){
        if(StringUtils.isEmpty(appUser.getSuperInviteCode())){
            return ServerResponse.createByErrorMessage("邀请码不能为空");
        }

        AppUser auser = new AppUser();auser.setMeInviteCode(appUser.getSuperInviteCode());
        List<AppUser> list = userService.selectAppUserList(auser);
        AppUser appUser1 = CollectionUtils.isEmpty(list) ? null : list.get(0);//根据上级邀请码 获取上级的数据
        if(appUser1 == null){
            return ServerResponse.createByErrorMessage("绑定失败，没有该邀请码");
        }
        AppUser appUser2 = userService.selectAppUserById(appUser.getTableId());
        if(!appUser2.getSuperInviteCode().equals(appUser.getSuperInviteCode())){
            return ServerResponse.createByErrorMessage("该邀请码不是该用户的上级");
        }
        if(appUser.getTableId() == appUser1.getTableId()){
            return ServerResponse.createByErrorMessage("绑定失败,推荐人不能写自己的邀请码");
        }

        String wechatUnionid = appUser1.getWechatUnionid();//获取wx id
        String wechatNickname = appUser1.getWechatNickname();//获取wx 昵称
        appUser.setSuperWechatUnionid(wechatUnionid);
        appUser.setSuperWechatNickname(wechatNickname);
        int i = userService.updateAppUser(appUser);
        if(i>0){
           return ServerResponse.createBySuccessMessage("绑定成功");
        }
        return ServerResponse.createByErrorMessage("绑定失败");
    }

}
